const path = require("path");
const {
  createFileWithPath,
  genPdfFile,
  sanitizeFileName,
  fetchWithRetry,
} = require("./utils.js");

const headers = {
  accept: "application/json, text/plain, */*",
  "accept-language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-US;q=0.6",
  priority: "u=1, i",
  "sec-ch-ua":
    '"Not A(Brand";v="8", "Chromium";v="132", "Google Chrome";v="132"',
  "sec-ch-ua-mobile": "?0",
  "sec-ch-ua-platform": '"macOS"',
  "sec-fetch-dest": "empty",
  "sec-fetch-mode": "cors",
  "sec-fetch-site": "same-site",
  cookie:
    "header_theme_version=CLOSE; CURRENT_BLACKGAP=0; buvid4=0AB028BC-3595-F2FE-64DF-1B4E0191E7A508541-023080618-ZuhD6dxC%2BOIGrr71yHriqw%3D%3D; buvid_fp_plain=undefined; enable_web_push=DISABLE; DedeUserID=354922193; DedeUserID__ckMd5=b6112e5ef321d162; FEED_LIVE_VERSION=V_WATCHLATER_PIP_WINDOW3; buvid3=70FECEA9-6DAF-DD79-0EBF-BDB46D6BE2A688144infoc; b_nut=1723107488; _uuid=7CAD4105B-713C-BE6F-B1910-DC1733318910F89101infoc; CURRENT_QUALITY=80; rpdid=|(u|JRkukRkR0J'u~klk~u~|~; hit-dyn-v2=1; PVID=1; OUTFOX_SEARCH_USER_ID_NCOO=360096520.65005505; is-2022-channel=1; fingerprint=245262acb313b0d56ccdb9aa03bee3d3; CURRENT_FNVAL=4048; LIVE_BUVID=AUTO4717358134144556; buvid_fp=869480788e14350a16c77f64df4d43dc; home_feed_column=5; enable_feed_channel=DISABLE; browser_resolution=1920-1088; b_lsid=9EAFC10C3_194FE3B9DFD; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3Mzk2OTEzMDgsImlhdCI6MTczOTQzMjA0OCwicGx0IjotMX0.aVk_3hUEPq-5H35A4DmWC_MHnxu69YzkHEkgjSfsPro; bili_ticket_expires=1739691248; SESSDATA=8b1c764a%2C1754984108%2Cc26bf%2A22CjCP9P0S-s-tlAtRGi0ds94TqWha7HRPEQq9gDtkJ-SLWEctGW9ndH61r5gJSRoAY54SVkJrUWpmVjh1M19nQ2hFcXE4eHMxTGptN3F6NmtmT0xWZGx5clBJZlYyVW9aa3ZWWlZsbzM1aUdJVHRHdl9QQVN1cUlRZ0JfZHVkdlV5NzROWlVOajB3IIEC; bili_jct=cf9705645e37a1f4bf14c4d62ec8ee04; bp_t_offset_354922193=1033342141843111936; sid=8gb1rl89",
  Referer:
    "https://www.bilibili.com/video/BV17tK5ekEXe/?spm_id_from=333.1387.upload.video_card.click&vd_source=938c0b778d95974fe38b61bb7e137001",
  "Referrer-Policy": "no-referrer-when-downgrade",
};

/**
 * 根据 Bvid 获取字幕
 * @param {*} bvid
 */
exports.fetchBiliSubtitle = async (bvid) => {
  const {
    data: {
      aid,
      cid,
      title,
      owner: { name },
    },
  } = await fetch(
    `https://api.bilibili.com/x/web-interface/view?bvid=${bvid}`,
    {
      method: "GET",
    }
  ).then((res) => res.json());

  await fetchSubtitleByAidCid({ aid, cid, name, title, bvid });
};

/**
 *  工具 aic, cid 获取字幕
 * @param {*} param0
 */
async function fetchSubtitleByAidCid({
  aid,
  cid,
  name,
  title,
  bvid,
  id,
  season_id,
}) {
  const queryStr = season_id ? `&ep_id=${id}&season_id=${season_id}` : "";
  const { data } = await fetchWithRetry(
    `https://api.bilibili.com/x/player/wbi/v2?aid=${aid}&cid=${cid}${queryStr}&isGaiaAvoided=false&web_location=1315873&dm_img_list=[%7B%22x%22:4269,%22y%22:4036,%22z%22:0,%22timestamp%22:6,%22k%22:110,%22type%22:0%7D,%7B%22x%22:3075,%22y%22:944,%22z%22:38,%22timestamp%22:1451,%22k%22:60,%22type%22:0%7D]&dm_img_str=V2ViR0wgMS4wIChPcGVuR0wgRVMgMi4wIENocm9taXVtKQ&dm_cover_img_str=QU5HTEUgKEFwcGxlLCBBcHBsZSBNMiwgT3BlbkdMIDQuMSlHb29nbGUgSW5jLiAoQXBwbG&dm_img_inter=%7B%22ds%22:[%7B%22t%22:2,%22c%22:%22YnB4LXBsYXllci1sb2FkaW5nLXBhbmVsIGJweC1zdGF0ZS1sb2FkaW%22,%22p%22:[442,8,639],%22s%22:[408,4059,2364]%7D],%22wh%22:[5155,4395,95],%22of%22:[405,810,405]%7D&w_rid=5f4e3d4e186c27d03054d3de27893e9f&wts=1735537237`,
    {
      headers: {
        ...headers,
        // Referer: `https://www.bilibili.com/video/${bvid}/?spm_id_from=333.1365.list.card_archive.click`,
      },
      body: null,
      method: "GET",
    }
  ).then((res) => {
    return res.json();
  });

  try {
    const url = data.subtitle.subtitles[0].subtitle_url;
    console.log(url);
    const { body } = await fetch(`https:${url}`, {
      method: "GET",
    }).then((res) => res.json());
    let content = body.map((i) => i.content).join(" ");

    let _path = `../script/${name}`;
    createFileWithPath(_path);
    _path = path.join(_path, `${sanitizeFileName(title)}_${bvid}.pdf`);
    // await fs.promises.writeFile(_path, content);
    genPdfFile(_path, content);
  } catch (error) {
    console.log(`"${bvid}",`);
  }
}

exports.fetchSubtitleByAidCid = fetchSubtitleByAidCid;

/**
 * 获取bilibili课程所有剧集
 * @param {*} season_id
 */
exports.fetchBilibiliCourse = async (season_id) => {
  const {
    data: { sections, title },
  } = await fetchWithRetry(
    `https://api.bilibili.com/pugv/view/web/season/v2?season_id=${season_id}&from_spmid=333.999.0.0`,
    {
      headers,
      body: null,
      method: "GET",
    }
  ).then((res) => res.json());
  const episodes = sections[0].episodes;

  for (const episode of episodes) {
    await this.fetchSubtitleByAidCid({
      ...episode,
      bvid: season_id,
      name: title,
      season_id,
    });
  }
};
